package com.zhenyi.liuxue.index;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.SqlPara;
import com.liuxue.common.model.LxPolicy;
import com.liuxue.common.model.LxSchool;
import com.liuxue.common.model.LxUser;
import com.zhenyi.liuxue.core.TemplateUtils;
import com.zhenyi.liuxue.interceptor.PermissionInterceptor;

import cn.hutool.core.date.DateUtil;

@Before({ PermissionInterceptor.class })
public class AuthController extends LXController {

	public void login() {
		render("/lx/index.html");
	}

	@Clear
	public void send() {
	}

	@Clear
	public void tk() {
		// Long schoolId = getParaToLong("schoolId");
		Long policyId = getParaToLong("policyId");
		if (policyId == null) {
			renderFailure();
			return;
		}
		LxPolicy policy = LxPolicy.dao.findById(policyId);
		if (policy == null) {
			renderFailure();
			return;
		}
		Long schoolId = policy.getSchoolId();
		if (schoolId == null) {
			renderFailure();
			return;
		}
		LxSchool school = LxSchool.dao.findById(schoolId);
		if (school == null) {
			renderFailure();
			return;
		}
		// String openId = getPara("openId");

		Kv kv = Kv.by("schoolId", schoolId);
		SqlPara sqlPara = lxDb.getSqlPara("LXFindSubscribeSchoolUsers", kv);
		List<LxUser> users = LxUser.dao.find(sqlPara);
		TemplateUtils templateUtils = new TemplateUtils();
		// System.out.println(templateUtils.getAccessToken());
		System.out.println(templateUtils.getAccessToken());
		String[] openIds = getParaValues("openId");

		if (openIds != null) {
			for (String openId : openIds) {
				templateUtils.send(openId, "亲爱的用户，您订阅的大学有最新通知", school.getName(), policy.getTitle(), DateUtil.today(),
						"点击查看详细信息", "/pages/app/schools/policyInfo/policyInfo?policyId=" + policyId);
			}
		} else {
			// for (LxUser lxUser : users) {
			// templateUtils.send(lxUser.getOpenId(), "亲爱的用户，您订阅的大学有最新通知",
			// school.getName(), policy.getTitle(),
			// DateUtil.today(), "点击查看详细信息",
			// "/pages/app/schools/policyInfo/policyInfo?policyId=" + policyId);
			// }
		}
		// templateUtils.send("o0OpG4xcUD-h3xKr_6NCF4DAJQM8",
		// "亲爱的用户，您订阅的大学有最新通知", "布里斯托大学", "布里斯托大学2019年语言课申请现已开放",
		// "2018年12月19日", "点击查看详细信息",
		// "/pages/app/schools/policyInfo/policyInfo?policyId=97");
		renderSuccess();
	}
}
